package logic

import (
	"context"
	"strconv"
	"three-sxp/common"
	"three-sxp/userrpc/userrpcclient"
	"time"

	"three-sxp/api/internal/svc"
	"three-sxp/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserLoginLogic) UserLogin(req *types.UserLoginRequest) (resp *types.UserLoginResponse, err error) {
	// todo: add your logic here and delete this line
	res, _ := l.svcCtx.UserRpc.UserLogin(l.ctx, &userrpcclient.UserLoginRequest{
		Mobile:   req.Mobile,
		Password: req.Password,
	})
	if res.Code != 200 {
		return &types.UserLoginResponse{
			Code: int(res.Code),
			Msg:  res.Msg,
		}, nil
	}
	token, _ := common.GetJwtToken(l.svcCtx.Config.AuthToken.AccessSecret, time.Now().Unix(), l.svcCtx.Config.AuthToken.AccessExpire, strconv.Itoa(int(res.UserId)))
	if token == "" {
		return &types.UserLoginResponse{
			Code: 400,
			Msg:  "token不能为空",
		}, nil
	}
	return &types.UserLoginResponse{
		Code:  int(res.Code),
		Msg:   res.Msg,
		Token: token,
	}, nil
}
